package config

import (
	"encoding/json"
	"go.uber.org/zap"
	"io"
	"net/http"
	"nvr-http-proxy/internal/domain"
)

type NvrEdge struct {
	url string
}

func NewNvrEdge(url string) *NvrEdge {
	return &NvrEdge{url: url}
}

func (e *NvrEdge) InitReadNvrConfig() ([]domain.NvrConfig, error) {
	request, err := http.NewRequest(http.MethodGet, e.url, nil)
	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		zap.S().Errorw("[读取nvr配置]调用盒子接口报错", err)
		return []domain.NvrConfig{}, err
	}
	// 读取后端服务响应
	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		zap.S().Errorw("[读取nvr配置]调用盒子接口报错", err)
		return []domain.NvrConfig{}, err
	}
	config := make(map[string]string)
	err = json.Unmarshal(responseBody, &config)
	if err != nil {
		zap.S().Errorw("[读取nvr配置]解析盒子接口返回结果报错", err)
		return []domain.NvrConfig{}, err
	}
	v := config["globalConfig"]
	config = make(map[string]string)
	err = json.Unmarshal([]byte(v), &config)
	if err != nil {
		zap.S().Errorw("[读取nvr配置]解析盒子接口返回结果报错", err)
		return []domain.NvrConfig{}, err
	}
	v = config["nvr_data"]
	var nvrConfig []domain.NvrConfig
	err = json.Unmarshal([]byte(v), &nvrConfig)
	if err != nil {
		zap.S().Errorw("[读取nvr配置]解析盒子接口返回结果报错", err)
		return []domain.NvrConfig{}, err
	}
	zap.S().Infof("调用盒子接口获取NVR的配置信息为:%v", config)
	return nvrConfig, nil
}
